package com.yupi.yuoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yuoj.annotation.AuthCheck;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.DeleteRequest;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.constant.UserConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.entity.Admins;
import com.yupi.yuoj.service.AdminsService;
import com.yupi.yuoj.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * 管理员接口
 *
 * @author yupi
 */
@RestController
@RequestMapping("/admins")
@Slf4j
public class AdminsController {

    @Resource
    private AdminsService adminsService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建管理员
     *
     * @param admins
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addAdmin(@RequestBody Admins admins, HttpServletRequest request) {
        if (admins == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 检查用户名是否已存在
        if (admins.getUsername() != null) {
            Admins existingAdmin = adminsService.lambdaQuery()
                    .eq(Admins::getUsername, admins.getUsername())
                    .one();
            if (existingAdmin != null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名已存在");
            }
        }
        // 检查邮箱是否已存在
        if (admins.getEmail() != null) {
            Admins existingAdmin = adminsService.lambdaQuery()
                    .eq(Admins::getEmail, admins.getEmail())
                    .one();
            if (existingAdmin != null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱已存在");
            }
        }
        boolean result = adminsService.save(admins);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newAdminId = admins.getId();
        return ResultUtils.success(newAdminId);
    }

    /**
     * 删除管理员
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteAdmin(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        Admins oldAdmin = adminsService.getById(id);
        ThrowUtils.throwIf(oldAdmin == null, ErrorCode.NOT_FOUND_ERROR);
        boolean b = adminsService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新管理员（仅管理员）
     *
     * @param admins
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateAdmin(@RequestBody Admins admins, HttpServletRequest request) {
        if (admins == null || admins.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 判断是否存在
        Admins oldAdmin = adminsService.getById(admins.getId());
        ThrowUtils.throwIf(oldAdmin == null, ErrorCode.NOT_FOUND_ERROR);
        
        // 检查用户名是否已被其他管理员使用
        if (admins.getUsername() != null && !admins.getUsername().equals(oldAdmin.getUsername())) {
            Admins existingAdmin = adminsService.lambdaQuery()
                    .eq(Admins::getUsername, admins.getUsername())
                    .ne(Admins::getId, admins.getId())
                    .one();
            if (existingAdmin != null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名已存在");
            }
        }
        
        // 检查邮箱是否已被其他管理员使用
        if (admins.getEmail() != null && !admins.getEmail().equals(oldAdmin.getEmail())) {
            Admins existingAdmin = adminsService.lambdaQuery()
                    .eq(Admins::getEmail, admins.getEmail())
                    .ne(Admins::getId, admins.getId())
                    .one();
            if (existingAdmin != null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱已存在");
            }
        }
        
        boolean result = adminsService.updateById(admins);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取管理员
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Admins> getAdminById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Admins admin = adminsService.getById(id);
        if (admin == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 不返回密码信息
        admin.setPassword_hash(null);
        return ResultUtils.success(admin);
    }

    /**
     * 分页获取管理员列表（仅管理员）
     *
     * @param current
     * @param size
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Admins>> listAdminByPage(@RequestParam long current, @RequestParam long size) {
        Page<Admins> adminPage = adminsService.page(new Page<>(current, size));
        // 不返回密码信息
        adminPage.getRecords().forEach(admin -> admin.setPassword_hash(null));
        return ResultUtils.success(adminPage);
    }

    /**
     * 根据用户名搜索管理员
     *
     * @param username
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/search/by-username")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Admins>> searchAdminsByUsername(
            @RequestParam String username,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        if (username == null || username.trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Page<Admins> adminPage = adminsService.lambdaQuery()
                .like(Admins::getUsername, username)
                .orderByDesc(Admins::getCreated_at)
                .page(new Page<>(current, size));
        // 不返回密码信息
        adminPage.getRecords().forEach(admin -> admin.setPassword_hash(null));
        return ResultUtils.success(adminPage);
    }

    /**
     * 根据邮箱搜索管理员
     *
     * @param email
     * @return
     */
    @GetMapping("/search/by-email")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Admins> getAdminByEmail(@RequestParam String email) {
        if (email == null || email.trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Admins admin = adminsService.lambdaQuery()
                .eq(Admins::getEmail, email)
                .one();
        if (admin != null) {
            // 不返回密码信息
            admin.setPassword_hash(null);
        }
        return ResultUtils.success(admin);
    }

    /**
     * 更新管理员状态
     *
     * @param id
     * @param status
     * @param request
     * @return
     */
    @PostMapping("/update/status")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateAdminStatus(
            @RequestParam Long id,
            @RequestParam String status,
            HttpServletRequest request) {
        if (id == null || id <= 0 || status == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 判断是否存在
        Admins admin = adminsService.getById(id);
        ThrowUtils.throwIf(admin == null, ErrorCode.NOT_FOUND_ERROR);
        
        admin.setStatus(Integer.valueOf(status));
        boolean result = adminsService.updateById(admin);
        return ResultUtils.success(result);
    }

    /**
     * 重置管理员密码
     *
     * @param id
     * @param newPassword
     * @param request
     * @return
     */
    @PostMapping("/reset/password")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> resetAdminPassword(
            @RequestParam Long id,
            @RequestParam String newPassword,
            HttpServletRequest request) {
        if (id == null || id <= 0 || newPassword == null || newPassword.trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 判断是否存在
        Admins admin = adminsService.getById(id);
        ThrowUtils.throwIf(admin == null, ErrorCode.NOT_FOUND_ERROR);
        
        // 这里应该对密码进行加密处理
        admin.setPassword_hash(newPassword); // 实际项目中需要加密
        boolean result = adminsService.updateById(admin);
        return ResultUtils.success(result);
    }

    /**
     * 批量删除管理员
     *
     * @param ids
     * @param request
     * @return
     */
    @PostMapping("/batch/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> batchDeleteAdmins(@RequestBody List<Long> ids, HttpServletRequest request) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = adminsService.removeByIds(ids);
        return ResultUtils.success(result);
    }

}